﻿using System.IO;
using System.Text;
using Microsoft.Practices.RecipeFramework;
using VSSDKAssist.Assets.Actions.Base;

namespace VSSDKAssist.Assets.Actions.VisualStudio
{
	/// <summary>
	/// Action thats creates a file from a string content
	/// </summary>
	public class CreateFileFromStringAction : ActionBase
	{
		#region Properties

		private string content;
		/// <summary>
		/// The string with the content of the item. In most cases it is a class
		/// generated using the T4 engine.
		/// </summary>
		[Input(Required = true)]
		public string Content
		{
			get { return content; }
			set { content = value; }
		}

		private string targetFileName;
		/// <summary>
		/// Name of the file where the item is to be stored.
		/// </summary>
		[Input(Required = true)]
		public string TargetFileName
		{
			get { return targetFileName; }
			set { targetFileName = value; }
		}
		#endregion

		#region Protected Implementation
		/// <summary>
		/// Called when [execute].
		/// </summary>
		protected override void OnExecute()
		{
			if(!File.Exists(targetFileName))
			{
				using(StreamWriter sw = new StreamWriter(this.TargetFileName, false, new UTF8Encoding(true, true)))
				{
					sw.WriteLine(this.Content);
				}
			}
		}

		/// <summary>
		/// Called when [undo].
		/// </summary>
		protected override void OnUndo()
		{
			if(File.Exists(this.TargetFileName))
			{
				File.Delete(this.TargetFileName);
			}
		}
		#endregion
	}
}